<?php


namespace App\Http\Service;


use Illuminate\Support\Facades\DB;

class SensitiveWordsService
{
    private $dict;

    public function __construct()
    {
        $this->dict = [];
        $words = $this->load();
        //构建词树
        foreach ($words as $_word) {
            $uWord = $this->unicodeSplit($_word);

            $pdict = &$this->dict;

            $count = count($uWord);
            for ($i = 0; $i < $count; $i++) {
                if (!isset($pdict[$uWord[$i]])) {
                    $pdict[$uWord[$i]] = [];
                }
                $pdict = &$pdict[$uWord[$i]];
            }

            $pdict['end'] = true;
        }
    }

    public function find($str)
    {
        $uStr = $this->unicodeSplit($str);
        $count = count($uStr);

        for ($i = 0; $i < $count; $i++) {
            $pdict = $this->dict;
            $char = strtolower($uStr[$i]);
            if (isset($pdict[$char])) {
                $pdict = $pdict[$char];
                for ($j = $i + 1; $j < $count; $j++) {
                    $char2 = strtolower($uStr[$j]);
                    if (isset($pdict[$char2])) {
                        if (isset($pdict['end'])) {
                            return true;
                        }
                        $pdict = $pdict[$char2];
                    } elseif (!preg_match("/[ +=*&$#@\"')(~_]/", $char2)) {
                        break;
                    }
                }
                if (isset($pdict['end'])) {
                    return true;
                }
            }
        }
        return false;
    }

    // 替换敏感词为*号，搜索深度默认为5
    public function filter($str, $maxDistance = 5)
    {
        if ($maxDistance < 1) {
            $maxDistance = 1;
        }
        $uStr = $this->unicodeSplit($str, false);

        $count = count($uStr);

        for ($i = 0; $i < $count; $i++) {
            // 每个字符的开始，都是重新从词典开始匹配，做到不放过句子中的任何敏感词
            $pdict = $this->dict;
            $char = strtolower($uStr[$i]);
            if (isset($pdict[$char])) {
                $pdict = $pdict[$char];

                $matchIndexes = array();

                for ($j = $i + 1, $d = 0; $d < $maxDistance && $j < $count; $j++, $d++) {
                    $char2 = strtolower($uStr[$j]);
                    if (isset($pdict[$char2])) {
                        if (isset($pdict['end'])) {
                            // 小串匹配，例：宝宝
                            $uStr[$i] = '*';
                            foreach ($matchIndexes as $k) {
                                if ($k - $i == 1) {
                                    $i = $k;
                                }
                                $uStr[$k] = '*';
                            }
                            $matchIndexes = array();
                        }
                        $matchIndexes[] = $j;
                        $pdict = $pdict[$char2];
                        $d = -1;
                    } else if (!preg_match("/[ +=*&$#@\"')(~_]/", $char2)) {
                        // 以特别的字符进行分割敏感词的手段也要匹配
                        // 例：大****麻，匹配：大麻
                        break;
                    }
                }

                if (isset($pdict['end'])) {
                    // 大串匹配，例：宝宝穿越记
                    $uStr[$i] = '*';
                    foreach ($matchIndexes as $k) {
                        if ($k - $i == 1) {
                            $i = $k;
                        }
                        $uStr[$k] = '*';
                    }
                }
            }
        }

        return implode($uStr);
    }

    private function unicodeSplit($str, $caseword = true)
    {
        if ($caseword) {
            $str = strtolower($str);
        }
        $ret = [];
        $len = strlen($str);
        for ($i = 0; $i < $len; $i++) {
            $c = ord($str[$i]);

            if ($c & 0x80) {
                if (($c & 0xf8) == 0xf0 && $len - $i >= 4) {
                    if ((ord($str[$i + 1]) & 0xc0) == 0x80 && (ord($str[$i + 2]) & 0xc0) == 0x80 && (ord($str[$i + 3]) & 0xc0) == 0x80) {
                        $uc = substr($str, $i, 4);
                        $ret[] = $uc;
                        $i += 3;
                    }
                } elseif (($c & 0xf0) == 0xe0 && $len - $i >= 3) {
                    if ((ord($str[$i + 1]) & 0xc0) == 0x80 && (ord($str[$i + 2]) & 0xc0) == 0x80) {
                        $uc = substr($str, $i, 3);
                        $ret[] = $uc;
                        $i += 2;
                    }
                } elseif (($c & 0xe0) == 0xc0 && $len - $i >= 2) {
                    if ((ord($str[$i + 1]) & 0xc0) == 0x80) {
                        $uc = strstr($str, $i, 2);
                        $ret[] = $uc;
                        $i += 1;
                    }
                }
            } else {
                $ret[] = $str[$i];
            }
        }
        return $ret;
    }

    private function load()
    {
        return DB::table('sensitive')->pluck('keyword')->toArray();
    }
}